<template>
  <div class="classify-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分类列表</span>
          <el-button type="primary" @click="handleAdd">新增分类</el-button>
        </div>
      </template>

      <el-table
        :data="list"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" min-width="180" />
        <el-table-column prop="code" label="分类编码" min-width="120" />
        <el-table-column label="图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.parent_id !== 0 && row.image"
              :src="row.image"
              :preview-src-list="[row.image]"
              fit="cover"
              class="category-image"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showFeaturedColumn"
          prop="is_featured"
          label="是否推荐"
          width="100"
        >
          <template #default="{ row }">
            <template v-if="row.parent_id !== 0">
              <el-switch
                v-model="row.is_featured"
                :active-value="1"
                :inactive-value="0"
                :loading="row.updating"
                @change="handleFeaturedChange(row)"
              />
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.parent_id !== 0"
              type="primary"
              link
              @click="handleEdit(row)"
              >编辑图片</el-button
            >
            <el-button
              v-if="row.parent_id === 0"
              type="success"
              link
              @click="handleAddSub(row)"
              >添加分类</el-button
            >
            <el-button
              type="danger"
              link
              :disabled="row.children && row.children.length > 0"
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加弹窗组件 -->
    <add-classify
      v-model="addDialogVisible"
      :parent-data="currentRow"
      @success="init"
    />

    <!-- 添加编辑图片弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑图片"
      width="500px"
      destroy-on-close
    >
      <el-form ref="editFormRef" :model="editForm" label-width="120px">
        <el-form-item label="分类图片">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：200x200px，支持jpg、png格式</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitting"
            @click="handleEditSubmit"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import {
  getList,
  deleteClassify,
  editFeatured,
  editImage
} from "@/api/classify/classify";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import AddClassify from "./AddClassify.vue";

const list = ref([]);

// 判断是否显示推荐列
const showFeaturedColumn = computed(() => {
  return list.value.some(item => item.children && item.children.length > 0);
});

// 获取列表数据
async function init() {
  try {
    const res = await getList();
    if (res.code === 200) {
      list.value = res.data;
    }
  } catch (error) {
    ElMessage.error("获取列表失败");
  }
}

// 删除分类
async function handleDelete(row) {
  // 如果有子分类，禁止删除
  if (row.children && row.children.length > 0) {
    ElMessage.warning("该分类下存在子分类，无法删除");
    return;
  }

  try {
    await ElMessageBox.confirm("确认删除该分类吗？", "提示", {
      type: "warning"
    });

    const res = await deleteClassify(row.id);
    if (res.code === 200) {
      ElMessage.success("删除成功");
      init(); // 重新加载列表
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
}

// 添加状态变量
const addDialogVisible = ref(false);
const currentRow = ref(null);

// 修改添加处理函数
function handleAdd() {
  currentRow.value = null;
  addDialogVisible.value = true;
}

// 修改添加子分类处理函数
function handleAddSub(row) {
  currentRow.value = row;
  addDialogVisible.value = true;
}

// 弹窗相关的状态
const editDialogVisible = ref(false);
const imageUrl = ref("");
const submitting = ref(false);
const uploadUrl = "http://127.0.0.1:2000/api/minio/uploadImages";
const editForm = ref({
  id: null,
  image: ""
});

// 修改编辑处理函数
function handleEdit(row) {
  editForm.value.id = row.id;
  imageUrl.value = row.image || "";
  editDialogVisible.value = true;
}

// 图片上传成功处理
function handleAvatarSuccess(res) {
  if (res.code === 200) {
    imageUrl.value = res.data;
    editForm.value.image = res.data;
  } else {
    ElMessage.error(res.message || "上传失败");
  }
}

// 提交编辑
async function handleEditSubmit() {
  if (!editForm.value.image) {
    ElMessage.warning("请上传图片");
    return;
  }

  submitting.value = true;
  try {
    const res = await editImage(editForm.value);
    if (res.code === 200) {
      ElMessage.success("更新成功");
      editDialogVisible.value = false;
      init(); // 刷新列表
    } else {
      ElMessage.error(res.message || "更新失败");
    }
  } catch (error) {
    ElMessage.error("更新失败");
  } finally {
    submitting.value = false;
  }
}

// 图片上传前的验证
function beforeUpload(file) {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    ElMessage.error("只能上传 JPG 或 PNG 格式的图片!");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
}

// 自定义上传处理
async function customUpload(options) {
  try {
    // 这里应该调用你的文件上传 API
    // const formData = new FormData();
    // formData.append('file', options.file);
    // const res = await uploadFile(formData);
    // if (res.code === 200) {
    //   imageUrl.value = res.data.url;
    //   form.value.image = res.data.url;
    // }

    // 临时模拟，实际使用时替换为真实的上传逻辑
    const reader = new FileReader();
    reader.readAsDataURL(options.file);
    reader.onload = e => {
      imageUrl.value = e.target.result;
      form.value.image = e.target.result;
    };
  } catch (error) {
    ElMessage.error("上传失败");
  }
}

// 提交更新
async function handleSubmit() {
  if (!form.value.image) {
    ElMessage.warning("请上传图片");
    return;
  }

  submitting.value = true;
  try {
    const res = await editImage({
      id: form.value.id,
      image: form.value.image
    });

    if (res.code === 200) {
      ElMessage.success("更新成功");
      dialogVisible.value = false;
      init(); // 刷新列表
    }
  } catch (error) {
    ElMessage.error("更新失败");
  } finally {
    submitting.value = false;
  }
}

// 处理推荐状态变更
async function handleFeaturedChange(row) {
  // 添加临时状态防止重复点击
  row.updating = true;
  try {
    const res = await editFeatured({
      id: row.id,
      featured: row.is_featured
    });
    if (res.code === 200) {
      ElMessage.success("更新成功");
    } else {
      // 如果失败，回滚状态
      row.is_featured = !row.is_featured;
      ElMessage.error(res.message || "更新失败");
    }
  } catch (error) {
    // 发生错误时回滚状态
    row.is_featured = !row.is_featured;
    ElMessage.error("更新失败");
  } finally {
    row.updating = false;
  }
}

onMounted(() => {
  init();
});
</script>

<style scoped>
.classify-list {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.category-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.avatar-uploader {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px;
  color: #8c939d;
  text-align: center;
}

.avatar {
  display: block;
  width: 178px;
  height: 178px;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.dialog-footer {
  margin-top: 20px;
}
</style>
